package com.hq.modeapp.ui;




import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.hq.modeapp.R;
import com.hq.modeapp.bean.News_Bean;
import com.hq.modeapp.tools.FileUtils;

/**
 * **********************************************************
 *  @内容摘要	：webview界面
 *
 *  @作者	：黄秋
 *  @创建时间	：2013-4-11 下午3:16:11 
 *  @历史记录	:
 *  @日期	: 2013-4-11 下午3:16:11 	修改人：黄秋
 *  @描述	:
 ***********************************************************
 */
public class WebView_Activity extends Activity  {
	private WebView mWebView;
	/** 网页正在加载 */
	private View mLoading;
	/** 显示当前正在加载的url */
	private TextView mUrl;
	/** 历史记录 */
	private List<String> mHistory = new ArrayList<String>();
	private News_Bean bean;
	private boolean isFirstLoad = true;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview_activity);
		mWebView = (WebView)findViewById(R.id.webview);
		mLoading = findViewById(R.id.loading);
		mUrl = (TextView) findViewById(R.id.url);
		 Intent intent = getIntent(); //得到跳转的intent
		  Bundle bundle = intent.getExtras();//获得bundle对象 ...Bundle就相当于HashMap
		  bean = (News_Bean) bundle.getSerializable("bean");
		initWebView();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mWebView != null) {
			mWebView.pauseTimers();
			if (isFinishing()) {
				mWebView.loadUrl("about:blank");
			}
			callHiddenWebViewMethod("onPause");
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mWebView != null) {
			mWebView.resumeTimers();
			callHiddenWebViewMethod("onResume");
		}
	}
	
	
	/** 初始化WebView */
	private void initWebView() {
		mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		//一下两个设置自适应屏幕的宽度显示，双击可放大缩小
		mWebView.getSettings().setUseWideViewPort(true); 
		mWebView.getSettings().setLoadWithOverviewMode(true); 
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setPluginsEnabled(true);
		// 设置是否可缩放
		mWebView.getSettings().setBuiltInZoomControls(true);

		mWebView.setWebViewClient(new WebViewClient() {

			/** 页面开始加载 */
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				mUrl.setText(url);
				mUrl.setVisibility(View.VISIBLE);
				if(isFirstLoad){
					mLoading.setVisibility(View.VISIBLE);
					isFirstLoad = false;
				}
				
			}

			/** 页面加载完成 */
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				mLoading.setVisibility(View.GONE);
				mWebView.setVisibility(View.VISIBLE);
				if (!mHistory.contains(url))
					mHistory.add(0, url);
				mUrl.setVisibility(View.GONE);
			};

			/** 页面跳转 */
			@Override
			public boolean shouldOverrideUrlLoading(WebView view,
					final String url) {
				if (FileUtils.isVideoOrAudio(url)) {
					Dialog dialog = new AlertDialog.Builder(WebView_Activity.this)
							.setIcon(android.R.drawable.btn_star)
							.setTitle("播放/下载").setMessage(url)
							.setPositiveButton("播放", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intent = new Intent(WebView_Activity.this,
											VideoPlayerActivity.class);
									intent.putExtra("path", url);
									intent.putExtra("title", "123");
									startActivity(intent);
								}
							}).setNeutralButton("下载", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
//									if (Environment.MEDIA_MOUNTED
//											.equals(Environment
//													.getExternalStorageState())) {
//										MainActivity activity = (MainActivity) getActivity();
//										String savePath = Environment
//												.getExternalStorageDirectory()
//												+ "/";
//										if (TextUtils.isEmpty(mTitle))
//											savePath += FileUtils
//													.getUrlFileName(url);
//										else {
//											savePath += mTitle
//													+ "."
//													+ FileUtils
//															.getUrlExtension(url);
//										}
//										activity.mFileDownload.newDownloadFile(
//												url, savePath);
//										Toast.makeText(
//												getActivity(),
//												"正在下载 .."
//														+ FileUtils
//																.getUrlFileName(savePath)
//														+ " ，可从本地视频查看进度！",
//												Toast.LENGTH_LONG).show();
//									} else {
//										Toast.makeText(getActivity(),
//												"请检测SD卡!", Toast.LENGTH_LONG)
//												.show();
//									}
								}
							}).setNegativeButton("取消", null).create();
					dialog.show();
					return true;
				}
				return false;
			};
		});

		/** 处理后退键 */
		mWebView.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView != null
						&& mWebView.canGoBack()) {
					if (mHistory.size() > 1) {
						mHistory.remove(0);
						mWebView.loadUrl(mHistory.get(0));
						return true;
					}
				}
				return false;
			}
		});
		
		mWebView.loadUrl(bean.getUrl());
		
	}

	// ~~~~~~~~~~~~~处理FLASH退出的问题 ~~~~~~~~

	private void callHiddenWebViewMethod(String name) {
		if (mWebView != null) {
			try {
				Method method = WebView.class.getMethod(name);
				method.invoke(mWebView);
			} catch (NoSuchMethodException e) {
			} catch (IllegalAccessException e) {
			} catch (InvocationTargetException e) {
			}
		}
	}

}
